package com.cxl.price.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.cxl.price.dao.ItemCatDao;
import com.cxl.price.util.FinalStr;
import com.cxl.price.util.SummerGlobals;
import com.summer.core.service.impl.BaseServiceImpl;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.ItemCat;
import com.taobao.api.request.ItemcatsGetRequest;
import com.taobao.api.response.ItemcatsGetResponse;

/**
 * @about: 淘宝类目 service 实现
 * @author: wwwlike
 * @create: 2011-07-03
 */
@Service
public class ItemCatServiceImpl extends BaseServiceImpl<com.cxl.price.bean.ItemCat, String, ItemCatDao>
		implements ItemCatService {

	@Resource
	public void setDao(ItemCatDao dao) {
		this.dao = dao;
	}
	
	public void addItemCats() throws Exception {
		
		String type=SummerGlobals.getProperty("top.type");
		String url=SummerGlobals.getProperty("top."+type+".url");
		String appkey=SummerGlobals.getProperty("top."+type+".appkey");
		String appsecret=SummerGlobals.getProperty("top."+type+".secret");
		TaobaoClient client=new DefaultTaobaoClient(url, appkey,appsecret);
		ItemcatsGetRequest req=new ItemcatsGetRequest();
		req.setFields("cid,parent_cid,name,is_parent,");
		importItemCatList(client,req,0L,null);
	}
	
	
	
	public void importItemCatList(TaobaoClient client,ItemcatsGetRequest req,Long parentid,com.cxl.price.bean.ItemCat patent) throws ApiException
	{
	
	
		req.setParentCid(parentid);
		ItemcatsGetResponse response = client.execute(req);
	
		List<ItemCat> cats=response.getItemCats();
		for(ItemCat cat:cats)
		{
			 com.cxl.price.bean.ItemCat itemcat=new com.cxl.price.bean.ItemCat();
			 itemcat.setCid(cat.getCid());
			 itemcat.setName(cat.getName());
			 itemcat.setIs_parent(cat.getIsParent());
			 itemcat.setItemCat(patent);
			 dao.save(itemcat);
			// System.out.println(itemcat.getName());
			 if(cat.getIsParent())
			 {
				 //可以查询出来一次匹配
				 importItemCatList(client, req, cat.getCid(), itemcat);
			 }
		}
	}

	public static void main(String[] args) throws Exception {
		new ItemCatServiceImpl().addItemCats();
	}

}
